//
//  SearchResultQAViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/11.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "QASquareCell.h"
#import "QAPublishViewController.h"
#import "QADetailViewController.h"

#import "SearchResultQAViewController.h"

@interface SearchResultQAViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableArray <CommonQAModel *>*dataArray;

@end

@implementation SearchResultQAViewController

- (instancetype)initWithKeyWord:(NSString *)keyWord {
    
    self = [super init];
    
    if (self) {
        self.keyWord = keyWord;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];

    [self initView];
    [self refreshParam];
    [self request_QAList];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

-(void)searchCallBack:(NSNotification *)Noti {
    
    self.keyWord = [Noti.userInfo objectForKey:@"keyWord"];
    [self refreshParam];
    [self request_QAList];
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [QASquareCell calculateHeightWithModel:self.dataArray[indexPath.row]];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QASquareCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QASquareCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    QADetailViewController *vc = [[QADetailViewController alloc] init];
    vc.mqId = self.dataArray[indexPath.row].mqId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"QASquareCell" bundle:nil] forCellReuseIdentifier:@"QASquareCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_QAList];
        }];
        
        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_QAList];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}


- (void)request_QAList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;

    //综合排序 1：综合 2：价格由高到低 3：价格由低到高  4热门
    [t setValue:self.keyWord forKey:@"searchName"];
    [t setValue:@"7" forKey:@"type"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SearchAll];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    NSArray *list = [resultDic valueForKey:@"list"];
                    if ([list isKindOfClass:[NSArray class]]) {
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_GoAsk btnTitle:@"去提问" didPressButton:^{
                                    
                                    QAPublishViewController *vc = [[QAPublishViewController alloc] init];
                                    [weakSelf.navigationController pushViewController:vc animated:YES];
                                }];
                                
                            }
                        }

                        for (NSDictionary *listDic in list) {
                            CommonQAModel *model = [CommonQAModel modelWithDictionary:listDic];
                            
                            NSArray *userAnswerList = [listDic valueForKey:@"userAnswerList"];
                            if ([userAnswerList isKindOfClass:[NSArray class]]) {
                                model.userAnswerList = @[].mutableCopy;
                                for (NSDictionary *aswDic in userAnswerList) {
                                    
                                    CommonAnswerModel *aswModel = [CommonAnswerModel modelWithDictionary:aswDic];
                                    [model.userAnswerList addObject:aswModel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }

                        [weakSelf.tableview reloadData];
                    }
                }
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
